

# 读取文件内容，处理异常
def read_file_content(file_path):
    try:
        with open(file_path, 'r', encoding='utf-8', errors='ignore') as f:
            return f.read()
    except FileNotFoundError:
        return None
    except Exception as e:
        raise Exception(f"读取文件 {file_path} 时出错：{str(e)}")

def read_file_content_byline(file_path):
    """逐行读取文件内容，返回行列表"""
    lines = []
    try:
        with open(file_path, 'r', encoding='utf-8', errors='ignore') as f:
            while True:
                line = f.readline()
                if not line:  # 到达文件末尾
                    break
                lines.append(line)
        return lines
    except FileNotFoundError:
        return None
    except Exception as e:
        raise Exception(f"读取文件 {file_path} 时出错：{str(e)}")


# 写入文件内容，处理异常
def write_file_content(file_path, lines):
    try:
        with open(file_path, 'w', encoding='utf-8') as f:
            f.writelines(lines)
        return True, f"文件 {file_path} 已成功更新。"
    except Exception as e:
        return False, f"写入文件 {file_path} 时出错：{str(e)}"



# 通用检查方法，返回是否满足条件及消息
def check_condition(file_path, patterns, condition_name, signal_name):
    """通用检查方法，返回是否满足条件及消息，包含匹配行信息"""
    lines = read_file_content_byline(file_path)
    if lines is None:
        return False, f"文件 {file_path} 未找到。"
    
    if isinstance(patterns, str):
        patterns = [patterns]  # 单一模式转为列表
    
    match_info = []
    for i, line in enumerate(lines, 1):  # 从 1 开始计数行号
        for pattern in patterns:
            if pattern in line:
                match_info.append(f"匹配行 {i}: {line.strip()}")
    
    if match_info:
        return True, f"信号 {signal_name} 在 {file_path} 中存在，{condition_name}满足。\n" + "\n".join(match_info)
    return False, f"信号 {signal_name} 在 {file_path} 中不存在 {' 或 '.join(patterns)}，{condition_name}不满足。"
